package handler

import (
	"fmt"
	"io"
	"iptv_server/v3/v2_src/handler/middleware"
	"iptv_server/v3/v2_src/utils/cache"
	"net/http"
	"strings"
	"time"
)

//	public static final String apiUrl_listremotes = "http://gate." + MyServerDomain + ":81/cgi-bin/tvbox_box1.sh?do=listremotes";
//
// http://tv1.server.lan:19999/api/tvbox_box1?do=listremotes&addme

func InitRecorder(mux *http.ServeMux,middles ...middleware.MiddleWare) {
	red := &recorder{
		store: cache.NewCache[time.Time]("tv address", time.Hour*24),//6->24
	}

	h := middleware.ApplyMiddles(red, middles...)
	mux.Handle("/api/tvbox_box1", h)
	mux.Handle("/api/tvbox_box1/", h)

	IP_STORE = red
}

type recorder struct {
	store *cache.Cache[time.Time]
}

func (red *recorder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	_ = r.ParseForm()
	action := r.Form.Get("do")
	addme := r.Form.Has("addme")
	if addme {
		addr := r.RemoteAddr
		addr = strings.Split(addr, ":")[0]
		red.add(addr)
	}

	switch action {
	case "listremotes":
		w.WriteHeader(http.StatusOK)
		io.WriteString(w, red.String())
	}
}

func (red *recorder) add(addr string) {
	red.store.Save(addr, time.Now())
}

func (red *recorder) update(addr string) {
	if _,_, ok := red.store.Get(addr); ok {
		red.store.Save(addr, time.Now())
	}
}

func (red *recorder) String() string {
	all := red.store.GetAll()
	builder := &strings.Builder{}
	for k, v := range all {
		builder.WriteString(k)
		builder.WriteString(fmt.Sprintf(" timestamp: %d\n", v.Unix()))
	}
	return builder.String()
}
